# -- coding:UTF-8 --

import logging
import random
import time
import json
import pyperclip
import requests
import pyautogui
import os,signal
import cv2
import sys
import urllib3
from clicknium import clicknium as cc, locator
import subprocess
from pathlib import Path
import glob
import chardet
import mysql.connector
import shutil
from configparser import ConfigParser
from datetime import datetime
import base64

# 创建解析器对象
config = ConfigParser()
 
# 读取配置文件
config.read('config.ini')

# db_user = config.get('database', 'user')
# db_password = config.get('database', 'password')
# db_host = config.get('database', 'host')
# db_name = config.get('database', 'db_name')
# db_port = config.getint('database', 'port') 

# telegram_path = config.get('telegram', 'path') 

telegram_path = "C:\\BaiduNetdiskDownload\\tg\\"

path = os.getcwd()

global_headers = {
    'Host': 'gateway.blum.codes',
    'sec-ch-ua': '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99", "Microsoft Edge WebView2";v="124"',
    'accept': 'application/json, text/plain, */*',
    'content-type': 'application/json',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://telegram.blum.codes',
    'sec-fetch-site': 'same-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'priority': 'u=1, i',
}

class BlumWorker:
    logger = logging.getLogger(__name__)

    current_token = ""

    current_tg_exe = ""

    zip_target_dir = ""

    def get_all_files(self, directory):
        files = []
        for root, _, filenames in os.walk(directory):
            for filename in filenames:
                files.append(os.path.join(root, filename))
        return files
    
    def request_telegram_portable(self):
        # # 此处要更新一下ID为0的，这种是一开始没有初始化好ID的，会通过一次刷新，把ID正常化
        # self.refreshToken(0)

        # # 首先查看token是否过期，如果没有过期则不用拉去，只用刷新一下就好
        # need_refresh_token = self.refreshToken(self.flag)

        # if not need_refresh_token:
        #     print("这个token无须进行UI刷新")
        #     return
        try:
            print("register account")

            # 解压文件
            # print(f'解压文件{self.flag}')
            # zip_path = telegram_path+str(self.flag)+".zip"

            # zip_target_dir = telegram_path+str(self.flag)
            
            # shutil.unpack_archive(zip_path, telegram_path)

            # 首先更换tdata文件，以此完成账号变化
            process = subprocess.Popen(self.current_tg_exe, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

            time.sleep(5)

            search_and_menu =  'images/search_and_menu3.png'

            try:
                search_and_menu_location = pyautogui.locateOnScreen(search_and_menu, minSearchTime=6.8, confidence=0.9)
            except:
                print('e-->')

            x, y = pyautogui.center(search_and_menu_location)
            x = x - 20
            pyautogui.click(x, y)

            saved_messages = 'images/saved_messages.png'

            saved_messages_location = pyautogui.locateCenterOnScreen(saved_messages, minSearchTime=5.8, confidence=0.9)
            
            pyautogui.click(saved_messages_location)

            write_message = 'images/write_message.png'

            write_message_location = pyautogui.locateCenterOnScreen(write_message, minSearchTime=5.8, confidence=0.9)

            pyautogui.click(write_message_location)

            time.sleep(0.5)

            pyperclip.copy('https://t.me/hamsTer_kombat_bot/start?startapp=kentId7363257665')

            pyautogui.hotkey('ctrl', 'v')

            time.sleep(2)

            send = 'images/send.png'

            send_location = pyautogui.locateCenterOnScreen(send, minSearchTime=5.8, confidence=0.9)

            pyautogui.click(send_location)

            time.sleep(1)

            try:
                lunch = 'images/hamster_lunch.png'
                lunch_location = pyautogui.locateCenterOnScreen(lunch, minSearchTime=5.8, confidence=0.9)
                pyautogui.click(lunch_location)
            except:
                print("eee1")

            time.sleep(3)


            try:
                ham_reg_ok = 'images/reg_ok.png'
                ham_reg_ok_x, ham_reg_ok_y = pyautogui.locateCenterOnScreen(ham_reg_ok, minSearchTime=5.8, confidence=0.9)

                #  x, y = pyautogui.center(search_and_menu_location)
                # x = x - 20
                # pyautogui.click(x, y)

                print(ham_reg_ok_x)
                print(ham_reg_ok_y)

                # reg_ok_location_x = reg_ok_location_x + 15

                pyautogui.click(ham_reg_ok_x, ham_reg_ok_y)
            except:
                print("clicked ok")

        
            # print("lunch_location  :" + lunch_location)
            # print("lunch_location_2:" + lunch_2_location)
            # if lunch_2_location is not None:
            #     lunch_location = lunch_2_location

            time.sleep(40)

            reg_ok = 'images/hamster_reg.png'

            reg_ok_location_x, reg_ok_location_y = pyautogui.locateCenterOnScreen(reg_ok, minSearchTime=5.8, confidence=0.9)

            #  x, y = pyautogui.center(search_and_menu_location)
            # x = x - 20
            # pyautogui.click(x, y)

            print(reg_ok_location_x)
            print(reg_ok_location_y)

            # reg_ok_location_x = reg_ok_location_x + 15

            pyautogui.click(reg_ok_location_x, reg_ok_location_y)

            time.sleep(5)

            create_account = 'images/hamster_reg2.png'

            create_account_location = pyautogui.locateCenterOnScreen(create_account, minSearchTime=5.8, confidence=0.9)

            pyautogui.click(create_account_location)

            time.sleep(5)

            # continue_pic = 'images/continue.png'

            # continue_pic_location = pyautogui.locateCenterOnScreen(continue_pic, minSearchTime=5.8, confidence=0.9)

            # pyautogui.click(continue_pic_location)

            # time.sleep(5)

            # 等待20秒，等将最新的token写到数据库
            time.sleep(30)

            # # 获取数据库里面最新的token记录
            # cnx = mysql.connector.connect(user=db_user, port=db_port, password=db_password,
            #                                 host=db_host, database=db_name)
            # # 使用cursor()方法获取操作游标 
            # cursor = cnx.cursor()

            # # SQL 插入语句
            # query = "SELECT * FROM blumtoken_temp ORDER BY `id` DESC LIMIT 1;"
            # # values = ('aa')
            # cursor.execute(query)

            # for (column1, column2) in cursor:
            #     print(column2)
            #     self.current_token = column2

            # # 关闭游标和连接
            # cursor.close()
            # cnx.close()
            
            # 关闭TG
            # 现场清理
            process.terminate()
            # process.kill()
            time.sleep(20)
            shutil.rmtree(self.zip_target_dir)
        except Exception as e1:
            print(f"An error occurred: {e1.with_traceback}")
            # 现场清理
            process.terminate()
            # process.kill()
            time.sleep(20)
            shutil.rmtree(self.zip_target_dir)
        finally:
            print('---------------------------------------------> 结束')
            # time.sleep(5)
            # print('---------------------------------------------> 开始关闭')
            

    # 查看是否有可以claim的挖矿结果 如果是，则收获
    def checkClainMint(self):
        print("检查挖矿结果")

        # 查看是否有可以claim的挖矿结果 如果是，则收获
    def checkClainMint(self):
        print("检查挖矿结果")

    # 解析token
    def parse_token(self, token):
        splited = token.split(".")
        return splited[1]
    
    def base64_parse_token(self, token):
        token += "=" * ((4 - len(token) % 4) % 4)
        decoded_string = base64.b64decode(token)
        return decoded_string.decode("utf-8")
    
    def search_directories(self, directory, search_term):
        for root, dirs, files in os.walk(directory):
            for dir in dirs:
                if dir == search_term:
                    # print(os.path.join(root, dir))
                    return os.path.join(root, dir)
    
    def _loop(self):
        print("Start......")
        # self.request_telegram_portable()


        all_files = self.get_all_files('C:\\BaiduNetdiskDownload\\tg2')
        # print(all_files)

        for temp_item in all_files:
            #解压文件
            # print(temp_item)
            shutil.unpack_archive(temp_item, "C:\\BaiduNetdiskDownload\\tg2\\temp")
            # shutil.copy2("C:\\BaiduNetdiskDownload\\Telegram.exe", "C:\\BaiduNetdiskDownload\\tg2\\temp\\*\\")

            # 使用示例
            tempdir = self.search_directories('C:\\BaiduNetdiskDownload\\tg2\\temp', 'tdata')
            # print(tempdir.replace("tdata",""))
            shutil.copy2("C:\\BaiduNetdiskDownload\\Telegram.exe", tempdir.replace("tdata",""))
            self.current_tg_exe = tempdir.replace("tdata","") + "Telegram.exe"
            # print("aaaaa : " + self.current_tg_exe)
            self.zip_target_dir = 'C:\\BaiduNetdiskDownload\\tg2\\temp'
            self.request_telegram_portable()

        # self.refreshToken(self.flag)
        # if self.current_token.strip() != "":
        #     self.fetchTasks()
        #     self.refreshToken(self.flag)
        #     self.getBalance()       
        # self.flag = self.flag + 1
        # if self.flag > self.accounts:
        #     self.flag = 1

if __name__ == '__main__':
    bw = BlumWorker()
    print('begin work......')
    while 1 == 1:
        bw._loop()
        # bw._loop()
    print('done.....')
